package com.starry.security.config;

import com.starry.security.filter.TokenAuthFilter;
import com.starry.security.filter.TokenLoginFilter;
import com.starry.security.security.DefaultPasswordEncoder;
import com.starry.security.security.TokenLogoutHandler;
import com.starry.security.security.TokenManager;
import com.starry.security.security.UnAuthEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

@Configuration
public class TokenWebSecurityConfig extends WebSecurityConfigurerAdapter {
	private TokenManager tokenManager;
	private RedisTemplate redisTemplate;
	private DefaultPasswordEncoder defaultPasswordEncoder;
	private UserDetailsService userDetailsService;

	@Autowired
	public TokenWebSecurityConfig(UserDetailsService userDetailsService,TokenManager tokenManager,
	           RedisTemplate redisTemplate,DefaultPasswordEncoder defaultPasswordEncoder                   ) {

		this.userDetailsService = userDetailsService;
		this.tokenManager = tokenManager;
		this.redisTemplate = redisTemplate;
		this.defaultPasswordEncoder = defaultPasswordEncoder;
	}


	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.exceptionHandling().authenticationEntryPoint(new UnAuthEntryPoint())//没有权限访问
				.and().csrf().disable()
				.authorizeRequests()
				.anyRequest().authenticated()
				.and().logout().logoutUrl("/admin/acl/index/logout")//退出路径
				.addLogoutHandler(new TokenLogoutHandler(tokenManager, redisTemplate))//退出处理器
				.and().addFilter(new TokenLoginFilter(authenticationManager(), redisTemplate, tokenManager))//添加认证过滤器
				.addFilter(new TokenAuthFilter(authenticationManager(), tokenManager, redisTemplate))//添加授权过滤器
				.httpBasic();
	}


	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {

		auth.userDetailsService(userDetailsService).passwordEncoder(defaultPasswordEncoder);
	}

	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("/api/**");
	}
}
